import java.util.Random;

//Tabs = 4
//************************************************************
//	COPYRIGHT 2011 Bread Zeppelin - ALL RIGHTS RESERVED
//
//This file is the product of Bread Zeppelin and cannot be 
//reproduced, copied, or used in any shape or form without 
//the express written consent of Bread Zeppelin.
//************************************************************
//
//	$ID: Concurrent_Assg6
//
//	$Date: Feb 13, 2012
//
//	Reason:
//
//*************************************************************

/** $Author: Ben Hare, Zach Huenink, Philipp Wittmaack, Peter Maresca */
/** $Revision: 1 */

//Default Package

/**
 * 
 */
public class SeatCustomer_Task implements Runnable {

	final CustomerParty customerParty;
	Restaurant restaurant = Restaurant.getInstance();
	WaitingList waitList = restaurant.getWaitingList();

	/**
	 * Creates a new SeatCustomer_Task while taking a CustomerParty.
	 * 
	 * @param customerParty
	 */
	SeatCustomer_Task(CustomerParty customerParty) {
		this.customerParty = customerParty;
	}

	/** 
	 * Seat the customer in a nice orderly fashion.
	 */
	@Override
	public void run() {

		//Task 2 - Seating a customer
		Table requestedTable = restaurant.requestTable( 
				customerParty.getPartySize() );

		if (requestedTable != null) {

			CustomerParty waitingParty = waitList.getCustomer( customerParty.getPartySize() );

			if (waitingParty != null) {
				
				// Finalize WaitTime Metric
				RestaurantMetrics.getInstance().finishWaitTime(waitingParty, System.currentTimeMillis());
				// Begin SeatTime Metric
				RestaurantMetrics.getInstance().beginSeatTime(waitingParty, System.currentTimeMillis());

				// Takes 10-15 sec to seat the customer
				int time = new Random(System.currentTimeMillis()).nextInt(5000);
				time = time + 10000;
				try { 
					if(time > 14500){
						Thread.currentThread().interrupt();
					}
					Thread.sleep(time/Simulator.simulationSpeed);
					
					waitingParty.occupyTable(requestedTable);
					System.out.println("	" + waitingParty.getName() + " is seated");
					
					// Finalize SeatTime Metric
					RestaurantMetrics.getInstance().finishSeatTime(waitingParty, System.currentTimeMillis());
					// Begin WaitingOrderTime Metric
					RestaurantMetrics.getInstance().beginWaitingToOrderTime(waitingParty, System.currentTimeMillis());
					

					//Should move to hooks
					CheckAndTakeOrder_Task takeOrder = new CheckAndTakeOrder_Task(waitingParty);
					restaurant.getWaitressExecutor().execute(takeOrder);
				} 
				catch (InterruptedException e) {
					customerParty.rageQuit();
					System.out.println(customerParty.getName() + " has left the" +
					" premises after waiting too long to be seated");

				}

			}

		} else {

			restaurant.getHostessExecutor().execute(this);

		}

	}
}
